package com.system.permissiondemo.service.impl;

import com.google.common.base.Preconditions;
import com.system.permissiondemo.common.RequestHolder;
import com.system.permissiondemo.entity.SysAclModule;
import com.system.permissiondemo.exception.CustomizeException;
import com.system.permissiondemo.mapper.SysAclModuleMapper;
import com.system.permissiondemo.param.AclModuleParam;
import com.system.permissiondemo.service.AclModuleService;
import com.system.permissiondemo.util.LevelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AclModuleServiceImpl implements AclModuleService {
    @Autowired
    private SysAclModuleMapper moduleMapper;
    /**
     * 部门添加
     * @param moduleParam
     */
    @Override
    public void save(AclModuleParam moduleParam) {
        //校验
        if (checkExist(moduleParam.getId(),moduleParam.getParentId(),moduleParam.getName())){
            throw new CustomizeException("同一层级下存在相同名称的权限模版");
        }
        SysAclModule aclModule = SysAclModule.builder().name(moduleParam.getName())
                                                        .parentId(moduleParam.getParentId())
                                                        .seq(moduleParam.getSeq())
                                                        .remark(moduleParam.getRemark())
                                                        .status(moduleParam.getStatus()).build();
        String parentLevel= getLevel(moduleParam.getParentId());
        aclModule.setLevel(LevelUtil.calculateLevel(parentLevel,moduleParam.getParentId()));
        aclModule.setOperator(RequestHolder.getCurrentUser().getUsername());// TODO
        aclModule.setOperatorIp(RequestHolder.getCurrentRequest().getRemoteAddr());// TODO
        aclModule.setOperatorTime(new Date());
        moduleMapper.insertSelective(aclModule);
    }
    /**
     * 部门更新
     * @param moduleParam
     */
    @Override
    public void update(AclModuleParam moduleParam) {
        //校验
        if (checkExist(moduleParam.getId(),moduleParam.getParentId(),moduleParam.getName())){
            throw new CustomizeException("同一层级下存在相同名称的权限模版");
        }
        SysAclModule before = moduleMapper.selectByPrimaryKey(moduleParam.getId());
        Preconditions.checkNotNull(before,"待更新的权限模版不存在");
        if (checkExist(moduleParam.getId(),moduleParam.getParentId(),moduleParam.getName())){
            throw new CustomizeException("同一层级下存在相同名称的权限模版");
        }
        SysAclModule after = SysAclModule.builder()
                .id(moduleParam.getId())
                .name(moduleParam.getName())
                .parentId(moduleParam.getParentId())
                .seq(moduleParam.getSeq())
                .remark(moduleParam.getRemark())
                .status(moduleParam.getStatus()).build();
        String parentLevel= getLevel(moduleParam.getParentId());
        after.setLevel(LevelUtil.calculateLevel(parentLevel,moduleParam.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());// TODO
        after.setOperatorIp(RequestHolder.getCurrentRequest().getRemoteAddr());// TODO
        after.setOperatorTime(new Date());
        updateWithChild(before,after);
    }
    /**
     * 权限模版更新前后变化
     * @param before
     * @param after
     */
    @Transactional
    public void updateWithChild(SysAclModule before, SysAclModule after){
        //判断是否需要更新子部门
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        //不一致的时候
        if (!after.getLevel().equals(before.getLevel())){
            List<SysAclModule> aclModules = moduleMapper.getChildDeptListByLevel(before.getLevel());
            if (!CollectionUtils.isEmpty(aclModules)){
                for (SysAclModule aclModule:aclModules){
                    String level = aclModule.getLevel();
                    if (level.indexOf(oldLevelPrefix)==0){
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        aclModule.setLevel(level);
                    }
                }
                moduleMapper.batchUpdateLevel(aclModules);
            }
        }
        moduleMapper.updateByPrimaryKey(after);
    }
    /**
     * 检查数据是否已存在：权限模版id，权限模版名称，上级权限模版id
     * @param aclModuleId
     * @param parentId
     * @param aclModuleName
     * @return
     */
    private boolean checkExist(Integer aclModuleId,Integer parentId,String aclModuleName ){
        return moduleMapper.countByNameAndParentId(aclModuleId,parentId,aclModuleName) > 0;
    }

    /**
     * 根据权限模版id获取上一级权限模版id
     * @param aclModuleId
     * @return
     */
    private String getLevel(Integer aclModuleId){
        SysAclModule aclmodule = moduleMapper.selectByPrimaryKey(aclModuleId);
        if (aclmodule == null){
            return null;
        }
        return aclmodule.getLevel();
    }
}
